<?php
/**
 * Created by PhpStorm.
 * User: zng
 * Date: 2020/3/25
 * Time: 14:36
 */
namespace app\api\service\order;

use app\api\model\order\ShoppingCart as ShoppingCartModels;

Class ShoppingCart{

    /**
     * 获取购物车总数量
     *
     * @return float
     */
    public function count()
    {
        return ShoppingCartModels::sum('number');
    }

    /**
     * 获取单条购物车
     * @param int $fid
     * @return mixed
     */
    public function get( int $fid )
    {
        return ShoppingCartModels::where('fid',$fid)->findOrEmpty();
    }

    /**
     * 添加购物车
     * @param int $fid
     * @param bool $update 是否更新
     * @param mixed $model 模型
     * @return bool
     */
    public function save(int $fid, bool $update, $model)
    {
        $number = ['inc', 1];
        if ( $update === false ) {
            $number = 1;
            $model->fid = $fid;
        }
        $model->number = $number;
        return $model->isUpdate($update)->save();
    }

    /**
     * 清空购物车
     *
     * @return bool
     */
    public function clean()
    {
        return ShoppingCartModels::where([])->delete();
    }

    /**
     * 购物车列表
     *
     * @return mixed
     */
    public function cart()
    {
        return ShoppingCartModels::with(['foods'])->selectOrFail();
    }

    /**
     * 购物车减去
     * int $id
     * @return bool
     */
    public function reduce(int $id)
    {
        $model = ShoppingCartModels::getOrFail($id);
        if ( $model->number <= 1 ) {
            return $model->delete();
        }
        $model->number = ['dec', 1];
        return $model->save();
    }

    /**
     * 确认订单
     *
     * @return mixed
     */
    public function confirm()
    {
        return ShoppingCartModels::with(['foods'])->selectOrFail();
    }

}